import router from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css"; // 引入样式文件
import pinia from "./store";
import useUserStore from "./store/modules/user";
import { nextTick } from "vue";

const userStore = useUserStore(pinia);
userStore.userInfo();

// console.log(router)
NProgress.configure({ showSpinner: false });
router.beforeEach(async (to: any, from: any, next: any) => {
  NProgress.start();
  let token = userStore.token;
  let username = userStore.username;
  // 已经登录，不能去login,这个token可能是坏的
  if (token) {
    if (to.path === "/login") {
      // console.log("login");
      next({ path: "/" });
    } else {
      if (username) {
        // console.log(username);
        // console.log(router.options.routes);
        next();
      } else {
        try {
          await userStore.userInfo();
          username = userStore.username;
          // console.log(to);
          // console.log(router.options.routes); // 输出全部路由
          next({ ...to, replace: true });
        } catch (error) {
          // token失效，如果token失效，那么是不可能获取到对应用户的信息的
          userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    // 未登录，只能去login
    if (to.path !== "/login") {
      next({ path: "/login", query: { redirect: to.path } });
    } else {
      next();
    }
  }
  // next();
});
router.afterEach((from: any, to: any, next: any) => {
  // console.log(from);
  NProgress.done();
});
